package sisdroid.framework.rest;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;

public class RestClientImpl implements RestClient
{
	
	 private static String convertStreamToString( InputStream is )
	 {
	        BufferedReader	reader	= new BufferedReader(new InputStreamReader(is));
	        StringBuilder	sb		= new StringBuilder();
	 
	        String line = null;
	        try
	        {
	        	while ( ( line = reader.readLine()) != null )
	        	{
	                sb.append(line );
	                sb.append( "\n" );
	            }
	        } 
	        catch ( Exception e )
	        {
	        	// Aktivt ingenting :-)
	        }
	        finally
	        {
	            try
	            {
	                is.close();
	            }
	            catch ( Exception e )
	            {
	            	// Stadig aktivt ingenting :-)
	            }
	        }
	        return sb.toString();
	    }


	@Override
	public String get( String URL ) 
	{
		String		reponsestring	= "You should never see this!";
		HttpClient	httpclient		= new DefaultHttpClient();
        HttpGet		request			= new HttpGet(URL); 
        
        HttpResponse response = null;
        try
        {
        	response		= httpclient.execute( request );
        	reponsestring	= convertStreamToString( response.getEntity().getContent() );
        	
        	
        }
        catch ( Exception e )
        {
        	reponsestring = "Terriblesorry .... will not work, don't know why !";        	
        }
 

		return reponsestring;
	}
	
	@Override
	public String post( String URL, String body ) 
	{
		byte[]			bodybytes		= body.getBytes();
		String			reponsestring	= "You should never see this!";
		HttpClient		httpclient		= new DefaultHttpClient();
        HttpPost		request			= new HttpPost( URL );
        BasicHttpEntity	httpbody		= new BasicHttpEntity();
        httpbody.setContent( new ByteArrayInputStream( bodybytes ) );
        //httpbody.setContentLength( bodybytes.length );
        httpbody.setContentType( "application/json" );
        request.setEntity( httpbody );
  
        
        HttpResponse response = null;
        try
        {
        	response		= httpclient.execute( request );
        	reponsestring	= convertStreamToString( response.getEntity().getContent() );
        }
        catch ( Exception e )
        {
        	reponsestring = "Terriblesorry .... will not work, don't know why !";        	
        }
 

		return reponsestring;
	}

	
}